//axios请求封装
import axios from "axios";
import { useSystemStore } from "@/store/system";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); //禁用进度环
const service = axios.create({
  baseURL: "/api",
  timeout: 20000 // 超时时间 单位是ms
});
// 2.请求拦截器
//发请求前做的一些处理，数据转化，配置请求头，设置token,设置loading等，按需添加
service.interceptors.request.use(
  (config) => {
    NProgress.start();
    const $systemStore = useSystemStore();
    const token = $systemStore.token;
    if (token) {
      config.headers.authorization = token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);
// 3.响应拦截器
service.interceptors.response.use(
  (response) => {
    // console.log("response: ", response);
    //接收到响应数据并成功后的一些共有的处理，关闭loading等
    NProgress.done();
    let msg = response.data.msg || response.data.message || "";
    switch (response.data.code) {
      case 200:
        // 成功
        // showSuccessToast(msg);
        break;
      case 400:
        // 参数错误
        showFailToast(msg);
        break;
      case 401:
        showFailToast(msg);
        // window.location.href = "/login";
        break;
      // default:
      //   Message.error(response.data.message);
    }

    return response.data;
  },
  (error) => {
    console.log("异常信息", error);
    /***** 接收到异常响应的处理开始 *****/
    if (error && error.response) {
      // 2.根据响应码具体处理
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          error.message = "登录凭证已失效，请重新登录";
          // window.location.href = "/login";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "请求错误,未找到该资源";
          break;
        case 405:
          error.message = "请求方法未允许";
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "系统异常";
          break;
        case 501:
          error.message = "网络未实现";
          break;
        case 502:
          error.message = "网络错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网络超时";
          break;
        case 505:
          error.message = "http版本不支持该请求";
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    } else {
      error.message = "连接服务器失败";
    }
    showFailToast(error.message);
  }
);
export default service;
